import { ref, computed, watch } from 'vue'
import type { CartItem, Product } from '../types'
import { addCart, updateCart, deleteCartMany, fetchCart } from '@/api/cart'
import { useAuthStore } from '@/stores/auth'

const STORAGE_KEY = 'shop_cart_v1'

function loadFromStorage(): CartItem[] {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    if (!raw) return []
    const parsed = JSON.parse(raw)
    if (Array.isArray(parsed)) return parsed as CartItem[]
    return []
  } catch {
    return []
  }
}

function saveToStorage(items: CartItem[]) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(items))
}

const itemsRef = ref<CartItem[]>(loadFromStorage())

watch(itemsRef, (val) => saveToStorage(val), { deep: true })

export function useCart() {
  const authStore = useAuthStore()
  const items = itemsRef

  const totalQuantity = computed(() => items.value.reduce((sum, it) => sum + it.quantity, 0))
  const totalPrice = computed(() => items.value.reduce((sum, it) => sum + it.quantity * Number(it.product.saleMoney || 0), 0))

  async function addToCart(product: Product, quantity: number = 1) {
    const existing = items.value.find((it) => String(it.product.id) === String(product.id))
    if (existing) {
      existing.quantity += quantity
      if (authStore.isLoggedIn) {
        try { await updateCart({ goodId: Number(product.id), count: existing.quantity }) } catch {}
      }
    } else {
      items.value.push({ product, quantity })
      if (authStore.isLoggedIn) {
        try { await addCart({ goodId: Number(product.id), count: quantity }) } catch {}
      }
    }
  }

  async function removeFromCart(productId: string | number) {
    items.value = items.value.filter((it) => String(it.product.id) !== String(productId))
    if (authStore.isLoggedIn) {
      try { await deleteCartMany([Number(productId)]) } catch {}
    }
  }

  async function setQuantity(productId: string | number, quantity: number) {
    const target = items.value.find((it) => String(it.product.id) === String(productId))
    if (!target) return
    target.quantity = Math.max(1, quantity)
    if (authStore.isLoggedIn) {
      try { await updateCart({ goodId: Number(productId), count: target.quantity }) } catch {}
    }
  }

  async function clearCart() {
    const ids = items.value.map(it => Number(it.product.id))
    items.value = []
    if (authStore.isLoggedIn && ids.length) {
      try { await deleteCartMany(ids) } catch {}
    }
  }

  return { items, totalQuantity, totalPrice, addToCart, removeFromCart, setQuantity, clearCart }
}

